# E:\Download\ChatRoomProject\Document\database.py

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, declarative_base
import yaml

# 声明 Base 类
Base = declarative_base()

# 全局变量存储 engine 和 SessionLocal
engine = None
SessionLocal = None
db_config = None


def init_database(config: dict):
    """
    根据 Nacos 配置初始化数据库连接
    :param config: 从 Nacos 加载的完整配置字典
    """
    global engine, SessionLocal, db_config
    db_config = config

    # 解析 MySQL 连接信息
    mysql_url = config['spring']['datasource']['url']
    username = config['spring']['datasource']['username']
    password = config['spring']['datasource']['password']

    # 转换 JDBC URL 到 SQLAlchemy 兼容格式
    sqlalchemy_url = f"mysql+pymysql://{username}:{password}@{mysql_url.replace('jdbc:mysql://', '')}"

    # 创建 engine 和 SessionLocal
    engine = create_engine(sqlalchemy_url)
    SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

    # 声明绑定 Base
    Base.metadata.bind = engine

    print(f"数据库已初始化: {sqlalchemy_url}")

def create_tables():
    """
    自动创建所有模型定义的表（如果不存在）
    """
    from model.resumes import Resume
    from model.interviews import Interview
    from model.questions import Question

    # 使用 create_all() 创建所有表（不会覆盖已有表）
    Base.metadata.create_all(bind=engine)
    print("数据库表已自动创建（如不存在）")